"""
故事服务模块
"""

from datetime import datetime
from typing import List, Optional
from loguru import logger

from ..models.story_model import Story, StoryType, Language
from ..models.api_model import StoryRequest, StoryResponse
from .deepseek_service import DeepSeekService


class StoryService:
    """故事服务类"""

    def __init__(self, deepseek_service: DeepSeekService):
        self.deepseek_service = deepseek_service
        self.stories_db: List[Story] = []

    async def generate_story(self, request: StoryRequest) -> StoryResponse:
        """生成单个故事"""
        try:
            logger.info(f"开始生成故事: {request.title}")
            response = await self.deepseek_service.generate_story(request)
            
            if response.success and response.story_id:
                story = Story(
                    id=response.story_id,
                    title=response.title or "",
                    content_zh=response.content_zh or "",
                    content_en=response.content_en or "",
                    story_type=request.story_type,
                    language=request.language,
                    quality_score=response.quality_score,
                    created_at=response.created_at
                )
                self.stories_db.append(story)

            return response

        except Exception as e:
            logger.error(f"故事生成异常: {str(e)}")
            return StoryResponse(
                success=False,
                message=f"故事生成异常: {str(e)}",
                created_at=datetime.now()
            )

    async def batch_generate_stories(self, requests: List[StoryRequest]) -> List[StoryResponse]:
        """批量生成故事"""
        logger.info(f"开始批量生成故事，共{len(requests)}个")
        responses = []
        
        for i, request in enumerate(requests):
            response = await self.generate_story(request)
            responses.append(response)
            
        return responses

    def get_story_by_id(self, story_id: int) -> Optional[Story]:
        """根据ID获取故事"""
        for story in self.stories_db:
            if story.id == story_id:
                return story
        return None

    def get_stories_by_type(self, story_type: StoryType) -> List[Story]:
        """根据类型获取故事列表"""
        return [story for story in self.stories_db if story.story_type == story_type] 